package com.example.speeddating.config;

import com.example.speeddating.annotaion.LoginAdmin;
import com.example.speeddating.annotaion.LoginUser;
import com.example.speeddating.entity.Admin;
import com.example.speeddating.entity.TokenEntity;
import com.example.speeddating.tool.StringTools;
import com.example.speeddating.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.reflect.Method;

@Slf4j
@Component
public class LoginAdminHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(LoginAdmin.class)&&parameter.getParameterType().isAssignableFrom(Admin.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        Method method = parameter.getMethod();
        String methodName = method.getName();
        //得到使用这个注解的方法名字
        log.info("methodName:{}",methodName);
        // header中获取用户token
        String token = request.getHeader("Authorization");
        log.info("token:{}",token);
        if (StringTools.isEmpty(token)){
            return null;
        }
        Long id = (Long.valueOf(JwtTokenUtil.getUserIdByToken(token)));
        String userName = JwtTokenUtil.getUserName(token);
        Admin admin = new Admin();
        admin.setId(id);
        admin.setNickname(userName);
        return admin;
    }
}
